<template>
  <el-dialog title="物料产品选择" v-model="props.findProductDialog" width="70%" align-center append-to-body>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-form :model="params">
          <el-form-item>
            <el-input v-model="params.productName" clearable placeholder="请输入分类名称"></el-input>
          </el-form-item>
        </el-form>
        <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" default-expand-all
                 :expand-on-click-node="false"/>
      </el-col>

      <el-col :span="19">
        <el-form :inline="true" :model="params">
          <el-form-item label="物料编码">
            <el-input v-model="params.materialProductCode" placeholder="请输入物料编码"></el-input>
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="params.materialName" placeholder="请输入物料名称"></el-input>
          </el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="primary" plain @click="paramsReset">重置</el-button>
        </el-form>

        <el-table :data="salesorder" @current-change="selectClick" highlight-current-row height="400px" max-height="400px">
          <el-table-column prop="materialProductCode" label="物料编码" width="100"/>
          <el-table-column prop="productName" label="物料名称" width="100"/>
          <el-table-column prop="specificationAndModel" label="规格型号" width="100"/>
          <el-table-column prop="unitName" label="单位" width="100"/>
          <el-table-column prop="material" label="物料/产品" width="100" v-slot="options">
            <span v-if="options.row.material == 0">物料</span>
            <span v-if="options.row.material == 1">产品</span>
          </el-table-column>
          <el-table-column prop="materialName" label="所属分类" width="100">
            <template #default="scope">
              {{ scope.row.materialName }}
            </template>
          </el-table-column>
          <el-table-column prop="creationTime" label="创建时间"/>
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination v-model:current-page="params.currentPage" v-model:page-size="params.pageSize"
                         background :default-page-size="params.pageSize" :page-sizes="pageSizes"
                         layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResult.total)"
                         @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <div>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {findMaterial, findmaterialManagement} from "@/apis/xms/index.js";
import {getPageUnits} from "@/apis/zyj/units.js";
import {ElMessage} from "element-plus";

const props = defineProps({
  findProductDialog: Boolean,
})
const emit = defineEmits(['selectProduct','close'])

const selectProduct =ref(null)

let data = ref([]);
const visible = ref(false) // 弹窗显示状态
const title = ref('') // 弹窗标题
let ids = ref([]) // 选中行的id数组
const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
const formdata = ref({   //弹窗表单数据
  materialProductCode: '',
  productName: '',
  specificationAndModel: '',
  unitId: '',
  materialId: '',
  materialName: '',
  status: '',
  setSafetyStock: '',
  creationTime: '',
})
const unitList = ref([]) // 单位列表

const pageResult = ref({}) // 表格分页数据
const pageSizes = [2, 5, 8, 10] // 分页大小

const salesorder = ref([{}]);
//初始化状态（设置默认值）
const params = ref({
  currentPage: 1,
  pageSize: 5,
  materialId: '',
  materialName: '',
  materialProductCode: '',
  productName: '',
})

const handleClose = () => {
  emit('close')
  //清空选中的数据
  selectProduct.value=null
}
const handleConfirm = () => {
  if (selectProduct.value==null){
    ElMessage.error("请选择数据")
  }else {
    emit('selectProduct', selectProduct.value)
    handleClose()
  }
}


// 参数搜索查询数据
const handleSearch = async () => {
  console.log(params.value)
  pageResult.value = await findmaterialManagement(params.value)
  salesorder.value = pageResult.value.records
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = (currentPage) => {
  params.value.currentPage = currentPage
  handleSearch() // 数据刷新
}

/**
 * 处理分页大小变化
 * @param size 分页大小
 */
const handleSizeChange = (size) => {
  params.value.pageSize = size
  handleSearch() // 数据刷新
}
//树形菜单点击事件
const defaultProps = {
  children: 'children',
  label: 'materialName',
  value: 'materialId'
}

const handleNodeClick = (dara, node, vnode, event) => {
  params.value.materialId = node.data.materialId;
  handleSearch();
}

onMounted(async () => {
  data.value = await findMaterial();//树形菜单
  pageResult.value = await findmaterialManagement(params.value) // 获取分页数据
  salesorder.value = pageResult.value.records // 获取表格数据

  // 获取单位列表
  await getPageUnits('', '', '-1', '-1').then(res => {
    unitList.value = res
  })
})

// 表格选中事件
const handleSelectionChange = (val) => {
  deleteDisabled.value = !val.length
  ids.value = val.map(item => item.materialNo) // 使用map方法过滤出选中行的logId数组
}

// table选择项发生变化时会触发该事件
const selectClick = (row) => {
  selectProduct.value=null
  selectProduct.value=row
}

/**
 * 重置搜索参数
 */
const paramsReset = () => {
  params.value = {
    currentPage: 1,
    pageSize: 5,
    materialName: '',
    materialProductCode: '',
    productName: '',
  }
  handleSearch();
}
</script>

<style scoped>
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}


.dialog-footer {
  margin-top: 20px;
  text-align: center;
}
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>